package com.kob.botrunningsystem.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Bot implements java.util.function.Supplier<Integer>{

    @Override
    public Integer get() {
        File file = new File("input.txt");
        Scanner sc = null;
        try {
            sc = new Scanner(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return nextMove(sc.next());
    }

    static class Cell{
        public int x,y;
        public Cell(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    private boolean check_tail_increasing(int step){//检验当前回合,蛇的长度是否增加
        if(step <= 10) return true;
        return step % 3 == 1;
    }

    public List<Cell> getCells(int sx, int sy, String steps ){
        steps = steps.substring(1,steps.length() - 1); // 去掉括号
        List<Cell> cells = new ArrayList<>();
        int[] dx = {-1, 0, 1, 0},dy = {0, 1, 0, -1};
        int x = sx,y = sy;
        int step = 0;
        cells.add(new Cell(x,y));
        for (int i = 0; i < steps.length(); i++ ) {
            int d =  steps.charAt(i) - '0';
            x += dx[d];
            y += dy[d];
            cells.add(new Cell(x,y));
            step ++;//第几回合
            if(!check_tail_increasing(step)){
                cells.remove(0);//蛇尾不增加就把蛇尾删掉
            }
        }
        return cells;
    }

    public Integer nextMove(String input) {
        String[] strings = input.split("#"); // 取出地图
        int[][] g = new int[13][14];
//        还原成功二维数组，地图信息
        for (int i = 0, k = 0 ; i < 13; i++) {
            for (int j = 0; j < 14; j++, k++) {
                if(strings[0].charAt(k) == '1'){
                    g[i][j] = 1;
                }
            }
        }

        int aSx = Integer.parseInt(strings[1]),aSy = Integer.parseInt(strings[2]);//我方起点坐标
        int bSx = Integer.parseInt(strings[4]),bSy = Integer.parseInt(strings[5]);//对手起点坐标

        //取出两条蛇的身体
        List<Cell> aCells = getCells(aSx, aSy, strings[3]);
        List<Cell> bCells = getCells(bSx, bSy, strings[6]);

        // 将两条蛇的身体的所有坐标设为1，表示为障碍物，不能走
        for (Cell a : aCells) g[a.x][a.y] = 1;
        for (Cell b : bCells) g[b.x][b.y] = 1;


        int[] dx = {-1, 0, 1, 0},dy = {0, 1, 0, -1};
        //判断四个方向可以走哪个方向
        for (int i = 0; i < 4; i++) {
            int x = aCells.get(aCells.size() - 1).x + dx[i];
            int y = aCells.get(aCells.size() - 1).y + dy[i];
            if(x >= 0 && x < 13 && y >= 0 && y <14){
                if(g[x][y] == 0) return i;
            }
        }
        return 0; //向上走
    }
}
